package com.whnk.pm.service.impl;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.whnk.common.config.Global;

import com.whnk.pm.domain.ProjectInfo;

import com.whnk.pm.dto.ProjectExcelExportDTO;

import com.whnk.pm.mapper.ProjectInfoMapper;

import com.whnk.pm.service.IProjectInfoService;

import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.whnk.common.support.Convert;

/**
 * 项目 服务层实现
 *
 * @author whwhnk
 * @date 2020-01-09
 */
@Service
public class ProjectInfoServiceImpl implements IProjectInfoService {
    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    private final static String globalprofile = Global.getDownloadPath();

    /**
     * 查询项目信息
     *
     * @param id 项目ID
     * @return 项目信息
     */
    @Override
    public ProjectInfo selectProjectInfoById(Integer id) {
        return projectInfoMapper.selectProjectInfoById(id);
    }

    /**
     * 查询项目列表
     *
     * @param projectInfo 项目信息
     * @return 项目集合
     */
    @Override
    public List<ProjectInfo> selectProjectInfoList(ProjectInfo projectInfo) {
        return projectInfoMapper.selectProjectInfoList(projectInfo);
    }

    /**
     * 新增项目
     *
     * @param projectInfo 项目信息
     * @return 结果
     */
    @Override
    public int insertProjectInfo(ProjectInfo projectInfo) {
        Date startTime = projectInfo.getStartTime();
        Date endTime = projectInfo.getEndTime();
        if (startTime != null && endTime != null) {
            String budgetCycle = String.valueOf(DateUtil.betweenDay(startTime, endTime, true) / 7);
            projectInfo.setBudgetCycle(budgetCycle);
        }

        return projectInfoMapper.insertProjectInfo(projectInfo);
    }

    /**
     * 修改项目
     *
     * @param projectInfo 项目信息
     * @return 结果
     */
    @Override
    public int updateProjectInfo(ProjectInfo projectInfo) {
        Date startTime = projectInfo.getStartTime();
        Date endTime = projectInfo.getEndTime();
        if (startTime != null && endTime != null) {
            String budgetCycle = String.valueOf(DateUtil.betweenDay(startTime, endTime, true) / 7);
            projectInfo.setBudgetCycle(budgetCycle);
        }
        return projectInfoMapper.updateProjectInfo(projectInfo);
    }

    /**
     * 删除项目对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteProjectInfoByIds(String ids) {
        List<ProjectInfo> projectInfoList = projectInfoMapper.selectProjectInfoByIds(Convert.toStrArray(ids));
        if (projectInfoList != null && projectInfoList.size() > 0) {
            List<String> projectIdList = projectInfoList.stream().map(k -> k.getProjectId()).collect(Collectors.toList());
            String[] projects = new String[projectIdList.size()];
            projectIdList.toArray(projects);
            //project_member_info
//            projectMemberInfoMapper.deleteProjectMemberInfoByIds(projects);
//
//            projectDetailInfoMapper.deleteProjectDetailInfoByProjectIds(projects);
        }

        return projectInfoMapper.deleteProjectInfoByIds(Convert.toStrArray(ids));
    }

    @Override
    public ProjectInfo selectProjectInfoByProjectId(String projectId) {
        return projectInfoMapper.selectProjectInfoByProjectId(projectId);
    }

    @Override
    public String exportExcel() {
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = dateTimeFormatter.format(localDate);

        File path = new File(globalprofile + "/");
        path.mkdirs();
        String fileName = path.getAbsolutePath() + "/project-info-" + dateStr + ".xlsx";
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为绿色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)20);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景颜色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short)15);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        ProjectInfo selectProject = new ProjectInfo();
        List<ProjectInfo> projectInfoList = projectInfoMapper.selectProjectInfoList(selectProject);

        List<ProjectExcelExportDTO> projectExcelExportDTOList = new ArrayList<>();
        Date date = new Date();
//        for (ProjectInfo projectInfo : projectInfoList) {
//            ProjectMemberInfo selectProjectMemberInfo = new ProjectMemberInfo();
//            ProjectMemberInfo projectMemberInfo = projectMemberInfoMapper.selectProjectMemberInfoById(projectInfo.getProjectId());
//
//            ProjectDetailInfo selectProjectDetailInfo = new ProjectDetailInfo();
//            selectProjectDetailInfo.setProjectId(projectInfo.getProjectId());
//            List<ProjectDetailInfo> projectDetailInfoList = projectDetailInfoMapper.selectProjectDetailInfoList(selectProjectDetailInfo);
//            for (ProjectDetailInfo projectDetailInfo : projectDetailInfoList) {
//                ProjectExcelExportDTO projectExcelExportDTO = new ProjectExcelExportDTO();
//                BeanUtils.copyProperties(projectDetailInfo, projectExcelExportDTO);
//                BeanUtils.copyProperties(projectInfo, projectExcelExportDTO);
//
//                //目前周数
//                projectExcelExportDTO.setCurrentWeek(String.valueOf(DateUtil.betweenDay(projectInfo.getStartTime(), date, true) / 7));
//
//                //时间进度
//                Long projectDay = DateUtil.betweenDay(projectInfo.getStartTime(), projectInfo.getEndTime(), true);
//                Long currentDay = DateUtil.betweenDay(projectInfo.getStartTime(), date, true);
//                projectExcelExportDTO.setTimeSchedule((BigDecimal.valueOf(currentDay).divide(BigDecimal.valueOf(projectDay), 2, RoundingMode.HALF_UP)).toPlainString());
//
//                projectExcelExportDTOList.add(projectExcelExportDTO);
//            }
//        }
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        File file = new File(fileName);
        EasyExcel.write(file, ProjectExcelExportDTO.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
                .doWrite(projectExcelExportDTOList);
        return file.getName();
    }

}

